package com.frame.project.core.shiro;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.frame.project.common.jwt.Audience;
import com.frame.project.common.jwt.JwtHelper;
import com.frame.project.core.exception.CodeEnum;
import com.frame.project.modules.test.sys.entity.SysUser;
import com.frame.project.modules.test.sys.service.SysUserService;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;


@Service
public class MyRealm extends AuthorizingRealm{

	private  static Logger logger = LogManager.getLogger(MyRealm.class);

	/**
	 * 延时加载（懒加载）。如果提前加载导致SysUserService类中的spring注解失效
	 * 可以参考此地址： https://blog.csdn.net/elonpage/article/details/78965176
	 */
	@Autowired
	@Lazy
	private SysUserService userService;
	
	@Autowired
	private Audience audience;
	
	
	/**
	 * 大坑！，必须重写此方法，不然Shiro会报错
	 */
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof JWTToken;
	}


	/**
	 * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的 
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Claims claims = JwtHelper.parseJWT(principals.toString(),audience.getBase64Secret());
		String userid = claims.get("userid").toString();
		SysUser sysUser = new SysUser();
		sysUser.setId(userid);
		SysUser user = userService.getUser(sysUser);
		
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addRoles(user.getRoles()); //添加角色
		simpleAuthorizationInfo.addStringPermissions(user.getSysPermission());  //添加权限
		return simpleAuthorizationInfo;
	}

	/**
	 * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
		String token = (String) auth.getCredentials();
		// 解密获得用户信息，用于和数据库进行对比
		Claims claims = null;
		try {
				claims = JwtHelper.parseJWT(token,audience.getBase64Secret());
		} catch (ExpiredJwtException e) {
            throw new AuthenticationException("令牌过期"); 
        } catch (UnsupportedJwtException e) {
            throw new AuthenticationException("令牌无效"); 
        } catch (MalformedJwtException e) {
            throw new AuthenticationException("令牌格式错误"); 
        } catch (SignatureException e) {
            throw new AuthenticationException("令牌签名无效"); 
        } catch (IllegalArgumentException e) {
            throw new AuthenticationException("令牌参数异常"); 
        } catch (Exception e) {
            throw new AuthenticationException("令牌错误"); 
        }
		
		String userid = claims.get("userid").toString();
		SysUser sysUser = new SysUser();
		sysUser.setId(userid);
		SysUser user = userService.getUser(sysUser);
		if (user == null) {
			throw new AuthenticationException(CodeEnum.CODE_404.getMessage());
		}
	/*	if (! JWTUtil.verify(token, username, userBean.getPassword())) {
			throw new AuthenticationException("Username or password error");
		}*/

		return new SimpleAuthenticationInfo(token, token, "my_realm");
	}

}
